<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';
import axios from 'axios';
import { ElDrawer, ElMessage, type FormInstance } from 'element-plus';

// 类型定义
interface ChartData {
  id: number;
  goodsId: number;
  goodsName: string;
  cost: number;
  wareHouseId: string;
  type: string;
  customerName: string;
  customerPhone: string;
  dealCount: number;
  dealTime: string;
  dealPurpose: string;
  goodsQuality: number;
  userId: number;
  userName: string;
}

interface Warehouse {
  id: number;
  name: string;
  address: string;
  createTime: string;
  decoration: string;
}

// 响应式数据
const chartData = ref<ChartData[]>([]);
const total = ref(0);
const warehouses = ref<Warehouse[]>([]);
const drawerVisible = ref(false);
const loading = ref(false);
const orderFormRef = ref<FormInstance>();

// 搜索表单
const searchForm = reactive({
  userName: '',
  customerName: '',
  goodsName: '',
  goodsQuality: null as number | null,
  type: '',
  customerPhone: ''
});

// 新增订单表单
const addOrderForm = reactive({
  type: '售出',
  goodsName: '',
  dealPurpose: '',
  cost: null as number | null,
  dealCount: null as number | null,
  customerName: '',
  customerPhone: '',
  selectedQuality: '优' as '优' | '中' | '差',
  warehouseId: ''
});

// 表单验证规则 - 添加了客户联系方式的必填验证
const formRules = {
  goodsName: [{ required: true, message: '请输入货物名称', trigger: 'blur' }],
  cost: [{ required: true, message: '请输入成交金额', trigger: 'blur' }],
  dealCount: [{ required: true, message: '请输入成交数量', trigger: 'blur' }],
  customerName: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
  customerPhone: [{ required: true, message: '请输入客户联系方式', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }]
};

// 格式化时间
const formatDate = (time: string) => {
  const date = new Date(time);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
};

// 获取订单数据
const getData = async () => {
  try {
    loading.value = true;
    const res = await axios.get("http://localhost:8080/order/findAll");
    if (res.data.code === 0) {
      chartData.value = res.data.data;
      total.value = res.data.total;
    }
  } catch (err) {
    console.error('获取订单数据失败:', err);
    ElMessage.error('数据加载失败');
  } finally {
    loading.value = false;
  }
};

// 获取仓库数据
const fetchWarehouses = async () => {
  try {
    const res = await axios.get('http://localhost:8080/warehouse/findAll');
    if (res.data.code === 0) {
      warehouses.value = res.data.data;
      if (warehouses.value.length > 0) {
        addOrderForm.warehouseId = warehouses.value[0].id.toString();
      }
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error);
    ElMessage.error('仓库加载失败');
  }
};

// 当前选中的仓库
const selectedWarehouse = computed(() => {
  return warehouses.value.find(wh => wh.id.toString() === addOrderForm.warehouseId) || null;
});

// 筛选表格数据
const filteredData = computed(() => {
  return chartData.value.filter(item => {
    return (
        (searchForm.userName ? item.userName.includes(searchForm.userName) : true) &&
        (searchForm.customerName ? item.customerName.includes(searchForm.customerName) : true) &&
        (searchForm.goodsName ? item.goodsName.includes(searchForm.goodsName) : true) &&
        (searchForm.goodsQuality !== null ? item.goodsQuality === searchForm.goodsQuality : true) &&
        (searchForm.type ? item.type === searchForm.type : true) &&
        (searchForm.customerPhone ? item.customerPhone.includes(searchForm.customerPhone) : true)
    );
  });
});

// 打开抽屉
const openDrawer = () => {
  // 重置表单
  Object.assign(addOrderForm, {
    type: '售出',
    goodsName: '',
    dealPurpose: '',
    cost: null,
    dealCount: null,
    customerName: '',
    customerPhone: '',
    selectedQuality: '优',
    warehouseId: warehouses.value[0]?.id.toString() || ''
  });

  if (warehouses.value.length === 0) {
    fetchWarehouses();
  }

  drawerVisible.value = true;
};

// 提交新订单
const submitOrder = async () => {
  // 验证表单
  if (!orderFormRef.value) return;

  try {
    // 验证表单字段
    const isValid = await orderFormRef.value.validate();

    if (!isValid) {
      ElMessage.warning('请填写完整信息');
      return;
    }

    // 转换货物质量为数字 (0:优, 1:中, 2:差)
    const qualityMap = { '优': 0, '中': 1, '差': 2 };
    const goodsQuality = qualityMap[addOrderForm.selectedQuality];

    const newOrder = {
      goodsName: addOrderForm.goodsName,
      cost: addOrderForm.cost,
      wareHouseId: addOrderForm.warehouseId,
      type: addOrderForm.type,
      customerName: addOrderForm.customerName,
      customerPhone: addOrderForm.customerPhone,
      dealCount: addOrderForm.dealCount,
      dealTime: new Date().toISOString(),
      dealPurpose: addOrderForm.dealPurpose || "未知",
      goodsQuality,
      userId: JSON.parse(localStorage.getItem("currentUser") || '{}').id || 1
    };
    console.log(newOrder)

    const res = await axios.post("http://localhost:8080/order/add", newOrder);
    if (res.data.code === 0) {
      ElMessage.success('订单添加成功');
      drawerVisible.value = false;
      await getData();
    } else {
      ElMessage.error(res.data.msg || '订单添加失败');
    }
  } catch (err) {
    // 表单验证失败时会进入catch，这里我们已经在validate处理了
    if (err instanceof Error) {
      console.error('表单验证失败:', err);
    } else {
      console.error('订单添加失败:', err);
      ElMessage.error('订单添加失败');
    }
  }
};


// 初始化
onMounted(() => {
  getData();
  fetchWarehouses();
});
</script>

<template>
  <div>
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-input v-model="searchForm.userName" placeholder="员工姓名" clearable />
      <el-input v-model="searchForm.customerName" placeholder="客户姓名" clearable />
      <el-input v-model="searchForm.goodsName" placeholder="货物名称" clearable />
      <el-input v-model="searchForm.customerPhone" placeholder="客户联系方式" clearable />

      <el-select v-model="searchForm.type" placeholder="交易类型" clearable>
        <el-option label="全部" value="" />
        <el-option label="售出" value="售出" />
        <el-option label="购入" value="购入" />
        <el-option label="划拨" value="划拨" />
      </el-select>

      <el-select v-model="searchForm.goodsQuality" placeholder="货物质量" clearable>
        <el-option label="全部" :value="null" />
        <el-option label="优" :value="0" />
        <el-option label="中" :value="1" />
        <el-option label="差" :value="2" />
      </el-select>

      <el-button type="primary" @click="openDrawer">新增订单</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="filteredData" height="600" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80">
        <template #default="scope">
          <el-tag type="primary">{{ scope.row.id }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="goodsName" label="货物名称" sortable />

      <el-table-column prop="type" label="交易类型" sortable>
        <template #default="scope">
          <el-tag :type="scope.row.type === '售出' ? 'success' : scope.row.type === '购入' ? 'info' : 'warning'">
            {{ scope.row.type }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="cost" label="成交金额" sortable />

      <el-table-column prop="dealCount" label="成交数量" sortable />

      <el-table-column prop="goodsQuality" label="货物质量" sortable>
        <template #default="scope">
          {{
            scope.row.goodsQuality === 0 ? '优' :
                scope.row.goodsQuality === 1 ? '中' : '差'
          }}
        </template>
      </el-table-column>

      <el-table-column prop="customerName" label="客户姓名" />
      <el-table-column prop="customerPhone" label="客户联系方式" />
      <el-table-column prop="wareHouseId" label="仓库ID" />

      <el-table-column prop="dealTime" label="交易时间" sortable>
        <template #default="scope">
          {{ formatDate(scope.row.dealTime) }}
        </template>
      </el-table-column>

      <el-table-column prop="userName" label="操作员" />
    </el-table>

    <!-- 新增订单抽屉 -->
    <el-drawer v-model="drawerVisible" title="新增订单" size="50%">
      <el-form
          ref="orderFormRef"
          :model="addOrderForm"
          :rules="formRules"
          label-width="120px"
          label-position="top"
      >
        <el-form-item label="交易类型" prop="type">
          <el-select v-model="addOrderForm.type">
            <el-option label="售出" value="售出" />
            <el-option label="购入" value="购入" />
          </el-select>
        </el-form-item>

        <el-form-item label="货物名称" prop="goodsName">
          <el-input v-model="addOrderForm.goodsName" placeholder="请输入货物名称" />
        </el-form-item>

        <el-form-item label="订单目的">
          <el-input
              v-model="addOrderForm.dealPurpose"
              placeholder="请输入订单目的"
              type="textarea"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成交金额" prop="cost">
              <el-input-number
                  v-model="addOrderForm.cost"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  controls-position="right"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成交数量" prop="dealCount">
              <el-input-number
                  v-model="addOrderForm.dealCount"
                  :min="1"
                  controls-position="right"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="customerName">
              <el-input v-model="addOrderForm.customerName" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 添加了客户联系方式的必填验证 -->
            <el-form-item label="客户联系方式" prop="customerPhone">
              <el-input
                  v-model="addOrderForm.customerPhone"
                  placeholder="请输入客户联系方式"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="产品质量">
          <el-select v-model="addOrderForm.selectedQuality">
            <el-option label="优" value="优" />
            <el-option label="中" value="中" />
            <el-option label="差" value="差" />
          </el-select>
        </el-form-item>

        <el-form-item label="相关仓库" prop="warehouseId">
          <el-select
              v-model="addOrderForm.warehouseId"
              style="width: 100%"
          >
            <el-option
                v-for="warehouse in warehouses"
                :key="warehouse.id"
                :label="warehouse.name"
                :value="warehouse.id.toString()"
            />
          </el-select>
          <div v-if="selectedWarehouse" class="warehouse-description">
            仓库地址: {{ selectedWarehouse.address }}<br>
            仓库描述: {{ selectedWarehouse.decoration }}
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="flex: auto; text-align: right;">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder">提交</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped>
.search-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.warehouse-description {
  margin-top: 10px;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.6;
  color: #666;
}


</style>